﻿using System;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hirham.OpenMI.Engine
{
  public class HirhamEmulator
  {
    Task T;
    DateTime CurrentTime;
    TimeSpan TimeStep;


    public HirhamEmulator(string FilePath, DateTime start, TimeSpan timeStep)
    {
      filepath = FilePath;
      CurrentTime = start;
      TimeStep = timeStep;
      Start();
    }


    public void Stop()
    {
      if (T != null) //Need to implement a cancellation token
      {
        T.Dispose();
      }
    }


    public void Start()
    {
      if (T==null)
        T = Task.Factory.StartNew(Run);  
    }

    private string filepath;


    private void Run()
    {
      string file1 =Path.Combine(filepath, "openmi_data_ready.txt");

      while (true)
      {
        bool dataIsReady = (File.Exists(file1));

        if (dataIsReady)
        {
          System.Threading.Thread.Sleep(100);

          CurrentTime = CurrentTime.Add(TimeStep);

          using (StreamWriter sw = new StreamWriter(Path.Combine(filepath, "hirham_data_ready_timestep.txt")))
          {
            sw.WriteLine( "//N HIRHAM write at (now:) " + CurrentTime.ToString("yyyy MM dd HH mm ss"));
          }

          using (StreamWriter sw = new StreamWriter(Path.Combine(filepath, "hirham_data_ready.txt")))
          {
            sw.WriteLine("//N HIRHAM write at (now:) " + CurrentTime.ToString("yyyy MM dd HH mm ss"));
          }
          File.Delete(file1);
        }
      }
    }
  }

}
